﻿import tkinter as tk, tkinter.ttk as ttk, tkinter.scrolledtext
import datetime
from unicodedata import name
import  ui_data

class MainFrame(tk.Frame):
    """信息主窗口"""
    def __init__(self, parent:tk.PanedWindow, UI ) -> None:
        super().__init__(parent, background="#CCCCCC" )
        self.UI  = UI
        self.showing = -1
        self.pLog = tkinter.scrolledtext.ScrolledText(self, state="disabled")
        self.pLog.pack(fill="both", expand= 1)

        self.LOG_ID = 0
        for c  in self.pack_slaves():
            c._name = "mainframe_log_" + c._name
        pass
        
    def log(self, t, m):
        """添加一条日志"""
        self.pLog.configure(state="normal")
        self.pLog.insert(tk.END,"%8d %s %s %s\n" %(self.LOG_ID, datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S.%f"), t, m))
        self.LOG_ID+=1
        self.pLog.configure(state="disabled")
    
    def add(self, data:ui_data.AData):
        """添加一个新的控件窗口 ，返回新创建的控件"""
        if(data.channel.type in ["TCPA", "TCPC", "UDP", "COM"]):
            f = data.protocol.UI(self, self.UI, data)
            return f
        else:
            return None
    
    def remove(self, data:ui_data.AData):
        """删除一个控件"""
        if(data.protocol.type == "RAW"):
            if(data.protocol.mf):
                data.protocol.mf.remove()
    
    def show(self, data:ui_data.AData = None):
        """显示控件"""
        
        for c  in self.pack_slaves():  ####.winfo_children():
            if c._name.startswith("mainframe"):
                c.pack_forget()
                break
        # else:
        #     self.pLog.pack_forget()
        if data:
            if(data.protocol.type == "RAW"):
                if data.protocol.mf:
                    data.protocol.mf.pack(fill="both", expand= 1)
                    return
        self.pLog.pack(fill="both", expand= 1)
        pass
    
    def enable(self, data:ui_data.AData):
        if(data.protocol.type == "RAW"):
            if(data.protocol.mf):
                data.protocol.mf.enable()
    
    def disable(self, data:ui_data.AData):
        if(data.protocol.type == "RAW"):
            if(data.protocol.mf):
                data.protocol.mf.disable()
